import plugin from "../../../lib/plugins/plugin.js"
import {segment} from "oicq";
import Yaml from '../Yaml/Yaml.js'
import _ from "underscore"

let rootPath = process.cwd()
let pluginPath = rootPath + '/plugins/fisticuffs-plugin/config/'
let appConfigPath = pluginPath + 'application.yaml'
let fistTechniquePath = pluginPath + 'fistTechnique.yaml'
let hitLocationPath = pluginPath + 'hitLocation.yaml'

const checkAbsoluteMasterFalse = async function (e, absoluteMaster) {
    if (absoluteMaster === null) {
        let msg = '请先发送【设置绝对权限】再使用功能！'
        if (e.isGroup) {
            e.reply([segment.at(e.user_id), msg])
        } else {
            e.reply(msg)
        }
        return false;
    }
    return true;
}

export class hit extends plugin {
    constructor() {
        super({
            name: '打架打架',
            dsc : '彻底疯狂',
            /** https://oicqjs.github.io/oicq/#events */
            event   : 'message',
            priority: 4998,
            rule    : [
                {
                    /** 命令正则匹配 */
                    reg: '^打人(仅我|所有人)可用$',
                    /** 执行方法 */
                    fnc: 'setHitAuthority',
                },
                {
                    /** 命令正则匹配 */
                    reg: '^本群(禁用|启用)打人$',
                    /** 执行方法 */
                    fnc: 'setHitStatus',
                },
                {
                    /** 命令正则匹配 */
                    reg: '^设置打人((b|B)(o|O)(t|T))名字(.*)$',
                    /** 执行方法 */
                    fnc: 'setBotName',
                },
                {
                    /** 命令正则匹配 */
                    reg: '^(.*)((d|D)(a|A)|(h|H)(i|I)(t|T)|打)((t|T)(a|A)|(h|H)(i|I)(m|M)|(h|H)(e|E)(r|R)|他|她|它)(.*)$',
                    /** 执行方法 */
                    fnc: 'HitOther'
                },
                {
                    /** 命令正则匹配 */
                    reg: '^((d|D)(a|A)|(h|H)(i|I)(t|T)|打)((w|W)(o|O)|(m|M)(e|E)|我)$',
                    /** 执行方法 */
                    fnc: 'HitMe'
                }
            ]
        })
    }

    // 设置群打人权限
    async setHitAuthority(e) {

        let appConfig = await Yaml.read(appConfigPath)
        let absoluteMaster = appConfig.absoluteMaster
        let botName = appConfig.botName
        let onlyMe = appConfig.onlyMe
        let isWrite = false

        if (!await checkAbsoluteMasterFalse(e, absoluteMaster)) {
            return true
        }

        if (e.user_id !== absoluteMaster) {
            if (!e.isGroup) {
                e.reply(`身份验证失败~`)
            }
            return false;
        }

        if (!botName) {
            await e.reply('我还没有名字,可以发送【设置打人bot名字XXX】给我设置名字哦~')
            return false;
        }

        if (e.msg.includes('仅我')) {
            if (!onlyMe) {
                appConfig.onlyMe = true
                isWrite = true
            }
            e.reply(`好的！${botName}只听主人的命令~`)
        } else {
            if (onlyMe) {
                appConfig.onlyMe = false
                isWrite = false
            }
            e.reply(`${botName}终于可以大展身手啦~`)
        }

        if (isWrite) {
            Yaml.write(appConfigPath, appConfig)
        }

        return false;
    }

    // 设置群打人状态
    async setHitStatus(e) {

        if (!e.isGroup) {
            return false;
        }

        let appConfig = await Yaml.read(appConfigPath)
        let absoluteMaster = appConfig.absoluteMaster
        let enableGroup = appConfig.enableGroup

        if (!await checkAbsoluteMasterFalse(e, absoluteMaster)) {
            return true
        }

        if (e.user_id !== absoluteMaster) {
            if (!e.isGroup) {
                e.reply(`身份验证失败~`)
            }
            return false;
        }

        if (enableGroup === false) {
            enableGroup = []
        }
        if (e.msg.includes('禁')) {
            enableGroup = _.difference(enableGroup, [e.group_id])
            e.reply(`本群已禁用打人功能~`)
        } else {
            enableGroup = _.union(enableGroup, [e.group_id])
            e.reply(`本群已启用打人功能~`)
        }

        appConfig.enableGroup = enableGroup
        Yaml.write(appConfigPath, appConfig)

        return false;
    }

    // 设置bot名字
    async setBotName(e) {

        let appConfig = await Yaml.read(appConfigPath)
        let absoluteMaster = appConfig.absoluteMaster

        if (!await checkAbsoluteMasterFalse(e, absoluteMaster)) {
            return true
        }

        if (e.user_id !== absoluteMaster) {
            if (!e.isGroup) {
                e.reply(`身份验证失败~`)
            }
            return false;
        }

        let botName = e.msg.replace(/设置打人([bB][oO][tT])名字/g, "").trim();

        if (botName.length > 20) {
            await e.reply(`名字稍有点长~`)
        } else if (botName.length === 0) {
            await e.reply(`我的名字呢？我的名字呢？我的名字呢？`)
        } else {
            appConfig.botName = botName
            Yaml.write(appConfigPath, appConfig)
            await e.reply(`设置好了！我以后就叫${botName}了~`)
        }
        return false;
    }

    // 打他
    async HitOther(e) {

        if (!e.isGroup) {
            e.reply(`你搁这儿打谁呢？我先给你一拳！`)
            return false;
        }

        if (!e.atme && !e.at) {
            e.reply([segment.at(e.user_id), ` 禁止虚空索敌！`])
            return false;
        }

        let appConfig = await Yaml.read(appConfigPath)
        let absoluteMaster = appConfig.absoluteMaster
        let botName = appConfig.botName
        let hitMaster = appConfig.hitMaster
        let maxHitTimes = appConfig.maxHitTimes
        let onlyMe = appConfig.onlyMe

        if (onlyMe) {
            return false;
        }

        if (!botName) {
            await e.reply('我还没有名字,可以发送【设置打人bot名字XXX】给我设置名字哦~')
            return false;
        }

        if (e.atall) {
            e.reply(`人太多！${botName}打不过！告辞！`);
            return true;
        }

        if (e.atme) {
            e.reply(`${botName}不能打自己！`);
            return true;
        }

        let fistTechnique = await Yaml.read(fistTechniquePath)
        if (_.isEmpty(fistTechnique)) {
            e.reply(`你站那别走！等我练练拳先！`);
            return true;
        }
        let fistTechniqueCount = fistTechnique.length

        let hitLocation = await Yaml.read(hitLocationPath)
        if (_.isEmpty(hitLocation)) {
            e.reply(`你先别动！我还没想好在哪里揍你！`);
            return true;
        }
        let hitLocationCount = hitLocation.length

        let hitOtherList = []
        let includeMaster = false

        for (let i = 0; i < e.message.length; i++) {
            let messageItem = e.message[i]
            if (messageItem.type === 'at') {
                hitOtherList.push(messageItem.qq)
                if (absoluteMaster === messageItem.qq) {
                    includeMaster = true
                }
            }
        }

        hitOtherList = _.uniq(hitOtherList)

        if (hitOtherList.length === 0) {
            e.reply(`${botName}要打谁来着？忘了！那就先不打了吧！`);
            return false
        }

        let you = ''
        let msgAdd = ''
        let maxHitTimeAdd = 0
        if (hitOtherList.length === 1) {
            if (includeMaster) {
                if (hitMaster) {
                    msgAdd = '是主人的话更要狠狠地打！'
                } else {
                    e.reply(`${botName}不能打主人`);
                    return false
                }
            }
            you = '你'
        } else if (hitOtherList.length > 1) {
            if (includeMaster) {
                if (hitMaster) {
                    msgAdd = '主人在里面！打人次数+1！'
                    maxHitTimeAdd += 1
                } else {
                    msgAdd = '主人在里面！把主人救出来！其他人继续打！'
                }
            }
            you = '你们'
        }

        let at = []
        for (let qq of hitOtherList) {
            at.push(segment.at(qq))
        }

        let hitTimes = Math.round(Math.random() * maxHitTimes);
        let msg = [
            at,
            `\n${you}今天的人品是【${hitTimes + 1}】，${botName}现在就打！把${you}${hitLocation[Math.round(Math.random() * (hitLocationCount - 1))]}打！${msgAdd}`
        ];
        hitTimes += maxHitTimeAdd

        async function sleep(time) {
            return new Promise(resolve => {
                setTimeout(resolve, time);
            })
        }

        e.reply(msg); //发送消息
        await sleep(1500) //延时
        for (let i = 0; i <= hitTimes; i++) {
            e.reply(fistTechnique[Math.round(Math.random() * (fistTechniqueCount - 1))]);
            await sleep(1500);
        }

        if (hitMaster && includeMaster) {
            e.reply(`主人！${botName}打疼你了吧！我不是故意的~也不是不小心的~我是故意不小心的~`);
        } else if (e.isMaster) {
            e.reply(`主人！${botName}打完啦！快奖励${botName}(っ●ω●)っ~`);
        } else {
            e.reply(`打完啦！`);
        }
        return false;
    }

    // 打我
    async HitMe(e) {

        if (!e.isGroup) {
            e.reply('你居然偷摸的自娱自乐！')
            return false;
        }

        let appConfig = await Yaml.read(appConfigPath)
        let maxHitTimes = appConfig.maxHitTimes
        let botName = appConfig.botName
        let onlyMe = appConfig.onlyMe

        if (onlyMe) {
            return false;
        }

        if (!botName) {
            await e.reply('我还没有名字,可以发送【设置打人bot名字XXX】给我设置名字哦~')
            return false;
        }

        let fistTechnique = await Yaml.read(fistTechniquePath)
        if (_.isEmpty(fistTechnique)) {
            e.reply(`你站那别走！等我练练拳先！`);
            return true;
        }
        let fistTechniqueCount = fistTechnique.length

        let hitTimes = Math.round(Math.random() * maxHitTimes);
        e.reply([segment.at(e.user_id), `\n今天的人品是【${hitTimes + 1}】，让${botName}满足你！`])
        await sleep(1500)

        async function sleep(time) {
            return new Promise(resolve => {
                setTimeout(resolve, time);
            })
        }

        for (let i = 0; i <= hitTimes; i++) {
            e.reply(fistTechnique[Math.round(Math.random() * (fistTechniqueCount - 1))]);
            await sleep(1500);
        }

        e.reply([segment.at(e.user_id), `够了吗！`]);

        return false;
    }
}
